/*
 * Copyright 2007 Sam Hough
 * 
 * This file is part of GWTS.
 *
 * GWTS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * GWTS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GWTS.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.redspr.gwts;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import com.gargoylesoftware.htmlunit.html.ClickableElement;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.util.StringUtils;

abstract public class AbstractHandler {
    void click(Tryst tryst, DomNode node) {
        while (node != null) {
            if (node instanceof ClickableElement) {
                ClickableElement he = (ClickableElement) node;
                he.fireEvent("click");
                break;
            }
            node = node.getParentDomNode();
        }
    }

    abstract void handle(Tryst tryst, DomNode node, HttpServletResponse out)
            throws IOException;

    // TODO 00 if onclick but not button or href make descendant visible
    // elements buttons?
    // TODO 00 put bookmark #bit as app URL
    protected void attr(Tryst tryst, HtmlElement node, PrintWriter out) {
        Iterator<DomNode> it = node.getAttributeEntriesIterator();
        while (it.hasNext()) {
            DomNode ha = it.next();
            at(out, ha.getNodeName(), ha.getNodeValue());
        }
    }

    protected void at(PrintWriter out, String name, String value) {
        out.print(' ');
        out.print(name);
        out.print("=\"");
        out.print(StringUtils.escapeXmlChars(value));// TODO UT " in value
        out.print('"');
    }

    // remove, replace, append - is it escaping!?
    protected DomNode getEventHandler(DomNode dm, String name) {
        while (dm.getParentDomNode() != null) {
            // XXX refactor this after unit tests done
            if (dm instanceof HtmlButton || dm instanceof HtmlAnchor) return null;
            if (dm.getEventHandler(name) != null)
                return dm;
            dm = dm.getParentDomNode();
        }
        return null;
    }
}
